package com.ruoyi.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.constant.ProjectConstants;
import com.ruoyi.system.domain.SysExperts;
import com.ruoyi.system.domain.SysProjectExpert;
import com.ruoyi.system.domain.SysProjectInfo;
import com.ruoyi.system.service.ISysExpertsService;
import com.ruoyi.system.service.ISysProjectExpertService;
import com.ruoyi.system.service.ISysProjectInfoService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysHistory;
import com.ruoyi.system.service.ISysHistoryService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 历史记录Controller
 *
 * @author riddou
 * @date 2022-04-15
 */
@RestController
@RequestMapping("/system/history")
public class SysHistoryController extends BaseController {
    @Autowired
    private ISysHistoryService sysHistoryService;

    @Autowired
    private ISysProjectInfoService sysProjectInfoService;

    @Autowired
    private ISysProjectExpertService sysProjectExpertService;

    @Autowired
    private ISysExpertsService sysExpertsService;

    /**
     * 查询历史记录列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysHistory sysHistory) {
        startPage();
        List<SysHistory> list = sysHistoryService.selectSysHistoryList(sysHistory);
        return getDataTable(list);
    }

    /**
     * 导出历史记录列表
     */
    @PreAuthorize("@ss.hasPermi('system:history:export')")
    @Log(title = "历史记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysHistory sysHistory) {
        List<SysHistory> list = sysHistoryService.selectSysHistoryList(sysHistory);
        ExcelUtil<SysHistory> util = new ExcelUtil<SysHistory>(SysHistory.class);
        util.exportExcel(response, list, "历史记录数据");
    }

    /**
     * 获取历史记录详细信息
     */
    @GetMapping(value = "/{historyId}")
    public AjaxResult getInfo(@PathVariable("historyId") Long historyId) {
        return AjaxResult.success(sysHistoryService.selectSysHistoryByHistoryId(historyId));
    }

    /**
     * 撤回操作
     */
    @Log(title = "历史记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysHistory sysHistory) {
        String rolename = sysHistory.getRolename();
        SysProjectInfo curProject = sysProjectInfoService.selectSysProjectInfoByProjectId(sysHistory.getProjectId());
        Long stage = sysHistory.getStage();
        //申报人操作
        if (ProjectConstants.ROLE_APPLICANT.equals(rolename)) {
            //申报撤回
            if (curProject.getStage() > stage && ProjectConstants.HIS_OPER_APPLICATE.equals(stage)) {
                return error("该项目已经在初审中，不能撤回申报！");
            }
            else {
                //申报撤回改变state
                curProject.setState(curProject.getState() - 1);
            }

            //申请验收撤回
            if (ProjectConstants.HIS_OPER_TO_ACCEPT.equals(stage) && !curProject.getStage().equals(stage)) {
                return error("该项目已经指派了专家，不能撤回申请！");
            }
            else {
                //申报验收改变stage
                curProject.setStage(curProject.getStage() - 1);
            }

        } else {
            SysProjectExpert reviewRecord = null;
            //审批通过撤回
            if (ProjectConstants.HIS_OPER_APPROVED.equals(stage)) {
                if (curProject.getStage() > sysHistory.getStage()) {
                    return error("项目已经开始实施跟踪，无法撤回!");
                }
                else {
                    //审批撤回改变state
                    curProject.setState(ProjectConstants.STATE_COMMITED);
                }
            }
            //验收通过撤回
            else if (ProjectConstants.HIS_OPER_ACCEPTED.equals(stage)){
                //项目撤回未待专家验收
                curProject.setStage(ProjectConstants.STAGE_TO_EXPERT_ACCEPT);

            }
            //审批不通过撤回
            else if (ProjectConstants.HIS_OPER_REVIEW_DENIED.equals(stage)) {
                //状态变为已提交
                curProject.setState(ProjectConstants.STATE_COMMITED);
                curProject.setStage(ProjectConstants.STAGE_TO_REVIEW);
            }
            //验收不通过撤回
            else {
                //状态变更为待验收
                curProject.setStage(ProjectConstants.STAGE_TO_EXPERT_ACCEPT);
            }
            //变回原审批信息
            reviewRecord = sysProjectExpertService.selectSysProjectExpertById(sysHistory.getReviewId());
            reviewRecord.setProjectState(ProjectConstants.STATE_REVIEWING);
            //设置未审核信息
            reviewRecord.setResult(ProjectConstants.RESULT_UNREVIEWED);
            //更新专家信息
            SysExperts expert = sysExpertsService.selectSysExpertsByExpertId(reviewRecord.getExpertId());
            expert.setCurReviewCount(expert.getCurReviewCount() + 1);
            //更新审核记录信息
            sysProjectExpertService.updateSysProjectExpert(reviewRecord);
            sysExpertsService.updateSysExperts(expert);
        }
        //更新历史记录中的项目阶段

        sysHistory.setState(ProjectConstants.HIS_STATE_INVALID);

        return toAjax(sysHistoryService.updateSysHistory(sysHistory) +
                sysProjectInfoService.updateSysProjectInfo(curProject));
    }

    /**
     * 删除历史记录
     */
    @PreAuthorize("@ss.hasPermi('system:history:remove')")
    @Log(title = "历史记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{historyIds}")
    public AjaxResult remove(@PathVariable Long[] historyIds) {
        return toAjax(sysHistoryService.deleteSysHistoryByHistoryIds(historyIds));
    }
}
